window.cardFunc = {};

function cardTypeInfo(cardType) {
    const info = {
        occupation: {
            header: "职业卡",
            cardData: occupationCards,
            handCardContainerClass: "occupation-card"
        },
        minorDevelopment: {
            header: "次要发展卡",
            cardData: minorDevelopmentCards,
            handCardContainerClass: "minor-development-card"
        },
    };

    return info[cardType];
}

function initializeCards(cardType) {
    const info = cardTypeInfo(cardType);
    const cardData = info.cardData;
    window.myData[`${cardType}CardsInHand`] = getRandomCards(cardData, 7);
    updateCardsInHand(cardType);
}

function updateCardsInHand(cardType) {
    const info = cardTypeInfo(cardType);
    const cardsContainer = $(`.${info.handCardContainerClass}`);
    cardsContainer.empty();

    const headerHtml = `
        <h3 class="hand-card-list-header" onclick="toggleCards('${cardType}')">${info.header} (点击此处展开)</h3>
    `;
    cardsContainer.append(headerHtml);

    const cardListContainer = $('<div class="card-list" style="display: none;"></div>');
    cardsContainer.append(cardListContainer);

    window.myData[`${cardType}CardsInHand`].forEach(card => {
        var costDisplay = card.cost ? (Object.keys(card.cost).length === 0 ? '无' : Object.entries(card.cost).map(([resource, amount]) => `${amount}${TypeName[resource]}`).join(', ')) : '';
        if (costDisplay && costDisplay.length > 0) {
            costDisplay = `<div class="hand-card-cost">花费: ${costDisplay}</div>`;
        }
        const conditionDisplay = card.condition && card.condition.length > 0 ? `<div class="hand-card-condition">条件: ${card.condition}</div>` : '';
        const scoreDisplay = card.scores ? `<div class="hand-card-score">分数: ${card.scores}</div>` : '';
        const cardHtml = `
            <div class="hand-card-item" id="${card.id}" onclick="selectCard('${cardType}', '${card.id}')">
                <div class="hand-card-title">${card.title} ${card.id}</div>
                ${conditionDisplay}
                ${costDisplay}
                ${scoreDisplay}
                <div class="hand-card-description">${card.description}</div>
            </div>
        `;
        cardListContainer.append(cardHtml);
    });
}

function toggleCards(cardType) {
    const info = cardTypeInfo(cardType);
    const cardListContainer = $(`.${info.handCardContainerClass} .card-list`);
    const isVisible = cardListContainer.is(":visible");

    cardListContainer.toggle();
    const headerText = `${info.header} (点击此处${isVisible ? "展开" : "折叠"})`;
    $(`.${info.handCardContainerClass} .hand-card-list-header`).text(headerText);
}

function selectCard(cardType, cardId) {
    const info = cardTypeInfo(cardType);
    if (!hasSubstatus(cardType + "Card")) {
        alert(`当前状态不能打出${info.header}`);
        return;
    }

    const card = window.myData[`${cardType}CardsInHand`].find(card => card.id === cardId);
    if (!card) {
        alert(`未找到该${info.header}！`);
        return;
    }

    const conditionFunction = cardFunc[card.id + 'Condition'];
    if (conditionFunction && !conditionFunction()) {
        return;
    }

    var cost = {};
    if (cardType == 'occupation') {
        let needFood = 0;
        const playedCardsCount = window.myData.occupationCards.length;
        if (hasSubstatus("subtype1")) {
            // 1食物->1职业卡，第一张职业卡免费。
            needFood = playedCardsCount > 0 ? 1 : 0;
        } else if (hasSubstatus("subtype2")) {
            // 2食物->1职业卡，前两张职业卡仅需支付1食物。
            needFood = playedCardsCount < 2 ? 1 : 2;
        }

        if (window.myData.food < needFood) {
            alert("你的食物不足，无法打出这张职业卡。");
            return;
        }

        let costConfirmText = needFood == 0 ? "你可以免费打出这张职业卡。是否继续？" : `你需要支付${needFood}个食物来打出这张职业卡。是否继续？`;
        if (!confirm(costConfirmText)) {
            return;
        }
        cost = {food : needFood};
    } else {
        cost = card.cost;
        if (!hasEnoughResources(cost)) {
            alert("资源不足，无法建造该次要发展卡！");
            return;
        }
    }

    if (!confirm(`确定选择"${card.title}"？`)) {
        return;
    }

    // 扣除资源
    deductResources(cost);

    window.myData[`${cardType}Cards`].push(card);
    window.myData[`${cardType}CardsInHand`] = window.myData[`${cardType}CardsInHand`].filter(card => card.id !== cardId);
    updateCardsInHand(cardType);
    addCardNode(cardType, card);

    applyCard(cardType, card);

    window.actionData.substatus.push("playedOneCard");

    updateResourceBar();
    updateFarm();
}

function addCardNode(cardType, card) {
    const info = cardTypeInfo(cardType);
    const cardContainer = $('#card-container');
    const cardElement = $('<div/>', { class: 'card' }).appendTo(cardContainer);

    const cardHeader = $('<div/>', {
        class: 'card-header',
        html: `${card.title} ${info.header}${card.scores ? ' <span class="card-score">分数：' + card.scores + '</span>' : ''}`
    }).appendTo(cardElement);

    const cardBody = $('<div/>', { class: 'card-body' }).appendTo(cardElement);

    const cardDescription = $('<p/>', {
        text: card.description,
        class: 'card-description'
    }).appendTo(cardBody);

    cardContainer.show();

    const eventHandler = cardFunc[card.id + 'EventHandler'];
    if (eventHandler) {
        eventHandler();
    }
}

function restoreCards(cardType) {
    // 恢复显示已打出的卡
    window.myData[`${cardType}Cards`].forEach(card => {
        addCardNode(cardType, card);
    });
}

function applyCard(cardType, card) {
    // 根据卡片的 ID 动态调用对应的逻辑
    const actionFunction = cardFunc[card.id + 'Action'];
    if (actionFunction) {
        actionFunction();
    }
}

//----- 卡牌的相关逻辑定义的样例
 
// condition为打出卡牌的条件判断
cardFunc.A010Condition = function() {
    if (window.myData.roomType !== "woodenHut") {
        alert("打出‘木棚’的条件未满足：仍然住在木屋");
        return false;
    }
    if (!hasSubstatus("majorDevelopmentCard")) {
        alert("打出‘木棚’的条件未满足：需要‘主要发展’行动");
        return false;
    }
    return true;
};

// action方法为打出卡牌立即需要结算的效果
cardFunc.A010Action = function() {

};

// eventHandler为卡牌对应的事件响应
cardFunc.A010EventHandler = function() {
    eventBus.addEventListener(EVENT_BEFORE_HOUSE_RENOVATION, function(event) {
        event.preventDefault();
        alert("‘木棚’次要发展卡已打出，你不能再翻新房屋！");
    });
};